package com.captain.special.栈队列;

import java.util.Deque;
import java.util.LinkedList;

/**
 * Des:
 * TODO *****
 *
 * @author XL
 * @Date 2022/5/19 9:43
 */
public class 验证二叉树的前序序列化331 {
    public static void main(String[] args) {
        System.out.println(new 验证二叉树的前序序列化331().isValidSerialization("9,3,4,#,#,1,#,#,2,#,6,#,#"));
    }

    public boolean isValidSerialization(String preorder) {
        int valid = 1;
        int i = 0;
        char[] str = preorder.toCharArray();
        int n = str.length;
        while (i < n) {
            if (valid == 0) {
                return false;
            }
            char c = str[i];
            if (c == ',') {
                i++;
            } else if (c == '#') {
                valid--;
                i++;
            } else {
                while (i < n && str[i] != ',') {
                    i++;
                }
                //槽位减1 + 2 = +1
                valid++;
                i++;
            }
        }
        return valid == 0;
    }
}
